package cn.com.tom.servlet;

import cn.com.tom.bean.Education;
import cn.com.tom.bean.User;
import cn.com.tom.service.EducationServie;
import cn.com.tom.service.UserService;
import cn.com.tom.service.WebsiteService;
import cn.com.tom.service.impl.EducationServiceImpl;
import cn.com.tom.service.impl.UserServiceImpl;
import cn.com.tom.service.impl.WebsiteServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/education/*")
public class EducationServlet extends BaseServlet {

    EducationServie servie = new EducationServiceImpl();
    UserService userService = new UserServiceImpl();
    WebsiteService websiteService = new WebsiteServiceImpl();

    public void admin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Education> list = servie.list();
        request.setAttribute("educations", list);
        forward(request, response, "admin/education.jsp");
    }

    public void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Education educationBean = new Education();
        BeanUtils.populate(educationBean, request.getParameterMap());
        if (servie.save(educationBean)) {
            forward(request, response, "admin/education.jsp");
        } else {
            forwardError(request, response, "保存失败");
        }
    }

    public void remove(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String[] idS = request.getParameterValues("id");
        List<Integer> list = new ArrayList();
        for (int i = 0; i < idS.length; i++) {
            list.add(Integer.valueOf(idS[i]));
        }
        if (servie.remove(list)) {
            redirect(request, response, "/education/admin");
        } else {
            forward(request, response, "删除失败");
        }
    }

    public void front(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = userService.list().get(0);
        request.setAttribute("user", user);
        request.setAttribute("educations", servie.list());
        request.setAttribute("website", websiteService.list().get(0));
        forward(request, response, "front/education.jsp");
    }
}
